//
//  ChangeMobileController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/23.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "ChangeMobileController.h"

@interface ChangeMobileController ()
@property (strong, nonatomic) IBOutlet UIButton *finshedBtn;
@property (strong, nonatomic) IBOutlet UIImageView *mobileImage;
@property (strong, nonatomic) IBOutlet UIImageView *codeImage;
@property (strong, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (strong, nonatomic) IBOutlet UITextField *mobileField;
@property (strong, nonatomic) IBOutlet UITextField *codeField;
@property (assign, nonatomic) NSInteger captchaCount;
@property (strong, nonatomic) NSTimer *timer;

@end

@implementation ChangeMobileController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"更改手机号码";
    __weak typeof(self)weakSelf = self;
    [self addLeftButtonWithImage:[UIImage imageNamed:@"返回箭头"] actionBlock:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    self.finshedBtn.layer.cornerRadius = self.mobileImage.layer.cornerRadius = self.getCodeBtn.layer.cornerRadius = self.codeImage.layer.cornerRadius = 5.0f;
    self.finshedBtn.layer.masksToBounds = self.mobileImage.layer.masksToBounds = self.codeImage.layer.masksToBounds = self.getCodeBtn.layer.masksToBounds = YES;
    self.captchaCount = 60;
    self.mobileField.clearButtonMode = UITextFieldViewModeWhileEditing;
}

// 获取验证码按钮
- (IBAction)getCodeAction:(UIButton *)sender {
    NSDictionary *dic = [[NSDictionary alloc]init];
    dic = @{@"mobile":self.mobileField.text};
    BOOL isMatchTwo = [self isValidateMobile:self.mobileField.text];
    
    if ([self.mobileField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码！"];
    }else if (!isMatchTwo || self.mobileField.text.length <11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码！"];
    }else
    {
        [HttpRequestManager getMethod:[NSString stringWithFormat:@"http://www.wplink.cn/index.php?g=Wap&m=Washcar&a=api_employee_get_code&mobile=%@",self.mobileField.text] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            NSLog(@"%@----------------",response);
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeCodeTime) userInfo:nil repeats:YES];
            if ([response[@"status"] isEqualToNumber:@1])
            {
                [SVProgressHUD showSuccessWithStatus:@"验证码发送成功！"];
                self.getCodeBtn.enabled = NO;
            }else if([response[@"status"] isEqualToNumber:@0])
            {
                [SVProgressHUD showErrorWithStatus:@"60秒内不能重复发送！"];
            }else{
                [SVProgressHUD showErrorWithStatus:@"验证码发送失败！"];
            }
            
        }];
    }
    
}

- (void)changeCodeTime
{
    if (self.captchaCount == 0) {
        self.getCodeBtn.enabled = YES;
        [self.timer invalidate];
        [self.getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        self.captchaCount = 60;
    }else{
        self.captchaCount = self.captchaCount - 1;
        NSString *lostTime = [NSString stringWithFormat:@"%lds",(long)self.captchaCount];
        [self.getCodeBtn setTitle:lostTime forState:UIControlStateNormal];
    }
}

-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

// 提交按钮
- (IBAction)finshButtonAction:(UIButton *)sender {
    BOOL isMatchTwo = [self isValidateMobile:self.mobileField.text];
    
    if ([self.mobileField.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码！"];
    }else if (!isMatchTwo || self.mobileField.text.length <11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码！"];
    }
    else if ([self.mobileField.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入密码！"];
    }else
    {
        [self webRequest_ChangeMobile];
    }
}

- (void)webRequest_ChangeMobile
{
    [self.mobileField resignFirstResponder];
    [self.codeField resignFirstResponder];
    NSString *mobileNO = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserMobileNO];
    NSDictionary *dict =  @{@"oldmobile" : mobileNO, @"newmobile" : self.mobileField.text, @"code" : self.codeField.text};
    [HttpRequestManager postMethod:KChangeMobileNoInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            [[NSUserDefaults standardUserDefaults] setObject:self.mobileField.text forKey:KUserDefaultsUserMobileNO];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [SVProgressHUD showSuccessWithStatus:@"更改成功"];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"更改失败"];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
